package com.pocketsweet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ContentView;
import com.pocketsweet.MLApplication;
import com.pocketsweet.MLContext;
import com.pocketsweet.R;
import com.pocketsweet.chat.ui.activity.BaseActivity;
import com.pocketsweet.model.MLArticle;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.ui.uilib.AutoListView;
import com.pocketsweet.ui.uilib.AutoListView.OnLoadListener;
import com.pocketsweet.ui.uilib.AutoListView.OnRefreshListener;
import com.pocketsweet.ui.uilib.HeaderLayout;
import com.pocketsweet.ui.uilib.HeaderLayout.HeaderStyle;
import com.pocketsweet.ui.uilib.HeaderLayout.onLeftContainerListener;
import com.pocketsweet.ui.uilib.LoadingDailog;
import com.pocketsweet.ui.uilib.ViewUtil;
import com.pocketsweet.ui.uilib.adapter.LikeRecommendAdapter;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

@ContentView(R.layout.activity_like_recommend)
public class LikeRecommend extends BaseActivity implements OnRefreshListener,
		OnLoadListener, OnItemClickListener {

	private AutoListView likeRecommendListview = null;
	private LikeRecommendAdapter likeRecommendAdapter;
	private List<MLArticle> articleList = new ArrayList<MLArticle>();
	private List<MLArticle> articleLikeList = new ArrayList<MLArticle>();
	private MLApplication mlApplication;
	private LinearLayout linBlank;
	private TextView tvBlankNoLove;
	private TextView tvBlankNoLover;
	private TextView tvBlankBg;
	private HeaderLayout header;
	private LoadingDailog mLoadingDialog;
	public static final int BEGIN_TO_LOADING = -1;
	private int skipDataCount = 0; // 忽略前N个对象
	public static final int MORE_DATA_MAX_COUNT = 100; // 每页10个对象
	private boolean isUpdateList = false; // 是否刷新列表

	// private BroadcastReceiver receiver = new BroadcastReceiver() {
	// @Override
	// public void onReceive(Context context, Intent intent) {
	// if (intent.getAction().equals(Main.ACTION_LIKE_RECOMMEND)) {
	// getUserLikerList();
	// likeRecommendAdapter.notifyDataSetChanged();
	// }
	// }
	// };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ViewUtils.inject(this);
		mlApplication = (MLApplication) getApplication()
				.getApplicationContext();
		initView();
		setHeaderFunction();
		mLoadingDialog = ToolKits.createLoadingDialog(LikeRecommend.this,
				"登陆中...");
		mLoadingDialog.setText("加载中");
		getUserLikerList(AutoListView.REFRESH);

		// initListview();
	}

	private void initView() {
		// TODO Auto-generated method stub
		likeRecommendListview = (AutoListView) findViewById(R.id.id_stickynavlayout_innerscrollview);
		linBlank = (LinearLayout) findViewById(R.id.linBlankNoRecommend);
		tvBlankBg = (TextView) findViewById(R.id.tvBlankBg);
		tvBlankNoLove = (TextView) findViewById(R.id.tvBlankNoLove);
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		tvBlankNoLover = (TextView) findViewById(R.id.tvBlankNoLover);
		likeRecommendAdapter = new LikeRecommendAdapter(this, articleList);
		likeRecommendListview.setAdapter(likeRecommendAdapter);
		likeRecommendAdapter.notifyDataSetChanged();
		likeRecommendListview.setPageSize(MORE_DATA_MAX_COUNT);
		// likeRecommendListview.setOnRefreshListener(this);
		likeRecommendListview.setOnLoadListener(this);
		likeRecommendListview.setOnItemClickListener(this);
	}

	public void setHeaderFunction() {
		header = (HeaderLayout) findViewById(R.id.mainHeader);
		header.init(HeaderStyle.IMG_TITLE_TEXT);
		header.setRightText("");
		header.setMiddleText("喜欢的推荐");
		header.setLeftContainerClickListener(new onLeftContainerListener() {

			@Override
			public void onClick() {
				LikeRecommend.this.finish();
			}
		});
	}

	@Override
	public void onStart() {
		super.onStart();
		// IntentFilter filter = new IntentFilter();
		// filter.addAction(Main.ACTION_LIKE_RECOMMEND);
		// registerReceiver(receiver, filter);
	}

	@Override
	public void onResume() {
		super.onResume();
	}
//
//	@Override
//	public void onDestroy() {
//		super.onDestroy();
//		// unregisterReceiver(receiver);
//	}

	/*
	 * 请求最近在线对象
	 */
	private void getUserLikerList(final int what) {
		// mLoadingDialog.show();
		linBlank.setVisibility(View.GONE);
		if (MLContext.getUserLikeSize("articleSize") != -1) { // 当sharepreference有点赞纪录时从本地获取
			ArrayList<String> tempArray = new ArrayList<String>();
			ArrayList<String> articleArray = new ArrayList<String>();
			tempArray = MLContext.getLike(MLContext.LIKE_TYPE_RECOMMEND);
			for (String articleId : tempArray) {
				if (!StringUtils.isEmpty(articleId)) {
					articleArray.add(articleId);
					// Log.e("===articleId==", "articlePreferences:" +
					// articleId);
				}
			}
			if (articleArray.size() <= 0) {
				likeRecommendListview.setNoData();
				if (what != AutoListView.LOAD) {
					tvBlankBg.setBackgroundResource(R.drawable.blank_no_like);
					tvBlankNoLove.setText(getResources().getString(
							R.string.blank_no_like));
					tvBlankNoLover.setText(getResources().getString(
							R.string.blank_no_like_else));
					linBlank.setVisibility(View.VISIBLE);
					tvBlankNoLover.setVisibility(View.VISIBLE);
					tvBlankNoLove.setVisibility(View.VISIBLE);
					return;
				}
			}
			if (what != BEGIN_TO_LOADING) {
				isUpdateList = true; // 如果不是首次加载数据，则该动作为刷新
			} else {
				likeRecommendListview.setRefreshData(); // 初始化显示loading动态图片
			}
			if (articleLikeList == null || articleLikeList.size() <= 0
					|| isUpdateList) { // userList为空或者动作为下拉刷新、往下加载时请求leanCloud

				final AVQuery<MLArticle> query = new AVQuery<MLArticle>(
						"MLArticle");
				skipDataCount = skipDataCount + MORE_DATA_MAX_COUNT; // 往下加载时忽略前一页
				if (what != AutoListView.LOAD) {
					skipDataCount = 0; // 刷新时不用忽略前面对象
				}
				query.whereContainedIn("objectId", articleArray);
				query.findInBackground(new FindCallback<MLArticle>() {

					@Override
					public void done(List<MLArticle> articleList,
							AVException arg1) {
						// mLoadingDialog.dismiss();
						if (arg1 == null) {
							// Log.e("===articleId==",
							// "articlePreferences:"
							// + String.valueOf(articleList.size()));
							if (articleList.size() <= 0) {
								if (what != AutoListView.LOAD) {
									tvBlankBg
											.setBackgroundResource(R.drawable.blank_no_like);
									tvBlankNoLove.setText(getResources()
											.getString(R.string.blank_no_like));
									tvBlankNoLover
											.setText(getResources()
													.getString(
															R.string.blank_no_like_else));
									linBlank.setVisibility(View.VISIBLE);
									tvBlankNoLover.setVisibility(View.VISIBLE);
									tvBlankNoLove.setVisibility(View.VISIBLE);
								}
								likeRecommendListview.setNoData();

							} else {
								linBlank.setVisibility(View.GONE);
								switch (what) {
								case AutoListView.REFRESH: // 下拉刷新时直接重新获取数据
									articleLikeList = articleList;
									likeRecommendListview.onRefreshComplete();
									// onLineListAdapter.setDatas(userList);
									break;
								case AutoListView.LOAD: // 加载更多时把新获取的数据添加到list列表
									likeRecommendListview.onLoadComplete();
									articleLikeList.addAll(articleList);
									break;
								case BEGIN_TO_LOADING: // Application无数据时首次加载，即重新获取数据
									articleLikeList = articleList;
									likeRecommendListview.onRefreshComplete();
									// onLineListAdapter.setDatas(userList);
									break;
								}
								likeRecommendListview
										.setResultSize(articleLikeList.size());
								likeRecommendAdapter.setDatas(articleLikeList);
								likeRecommendAdapter.notifyDataSetChanged();
								isUpdateList = false; // 刷新完毕，设为false
								// articleLikeList = articleList;
								// likeRecommendAdapter.setDatas(articleLikeList);
								// likeRecommendAdapter.notifyDataSetChanged();
								// int listViewHeight = ViewUtil
								// .setListViewHeightBasedOnChildren1(likeRecommendListview);
							}
						} else {
							// Log.e("＝＝错误", "查询点赞错误: " + arg1.getMessage());
							likeRecommendListview.setNoData();

							if (articleLikeList.size() <= 0) {

								linBlank.setVisibility(View.VISIBLE);
								tvBlankNoLover.setVisibility(View.GONE);
								tvBlankBg
										.setBackgroundResource(R.drawable.network_error);
								tvBlankNoLove.setText(getResources().getString(
										R.string.blank_network_error));
								linBlank.setOnClickListener(new OnClickListener() {

									@Override
									public void onClick(View arg0) {
										getUserLikerList(BEGIN_TO_LOADING);
									}
								});
							} else {
								ToolKits.toast(LikeRecommend.this, "网络错误");
							}
						}
					}
				});

			} else {
				// mLoadingDialog.dismiss();
				linBlank.setVisibility(View.VISIBLE);
				tvBlankNoLover.setVisibility(View.VISIBLE);
				// articleLikeList = null;
				// likeRecommendAdapter.setDatas(articleLikeList);
				// likeRecommendAdapter.notifyDataSetChanged();
			}
		} else {
			likeRecommendListview.setNoData();
			tvBlankBg.setBackgroundResource(R.drawable.blank_no_like);
			tvBlankNoLove.setText(getResources().getString(
					R.string.blank_no_like));
			tvBlankNoLover.setText(getResources().getString(
					R.string.blank_no_like_else));
			linBlank.setVisibility(View.VISIBLE);
			tvBlankNoLover.setVisibility(View.VISIBLE);
			tvBlankNoLove.setVisibility(View.VISIBLE);
		}
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLoad() {
		// TODO Auto-generated method stub
		getUserLikerList(AutoListView.LOAD);

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		getUserLikerList(AutoListView.REFRESH);
		likeRecommendListview.setOnRefreshListener(this);
	}
}